package com.taotao.service.Impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.HttpClientUtil;
import com.taotao.common.utils.JsonUtils;
import com.taotao.mapper.TbContentMapper;
import com.taotao.pojo.TbContent;
import com.taotao.pojo.TbContentExample;
import com.taotao.service.ContentService;

@Service
public class ContentServiceImpl implements ContentService {

	@Autowired
	private TbContentMapper contentMapper;
	
	@Value("${REST_BASE_URL}")
	private String REST_BASE_URL;
	@Value("${REST_CONTENT_SYN_URL}")
	private String REST_CONTENT_SYN_URL;
	
	@Override
	public EUDataGridResult getListByContentCategoryId(Long categoryId, int page, int rows) {
		PageHelper.startPage(page, rows);
		TbContentExample example=new TbContentExample();
		example.createCriteria().andCategoryIdEqualTo(categoryId);
		List<TbContent> list = contentMapper.selectByExample(example);
		EUDataGridResult euDataGridResult = new EUDataGridResult();
		euDataGridResult.setTotal(list.size());
		euDataGridResult.setRows(list);
		return euDataGridResult;
	}

	@Override
	public TaotaoResult saveContent(TbContent content) throws Exception {
		
		Date date = new Date();
		content.setUpdated(date);
		content.setCreated(date);
		contentMapper.insert(content);
		
		//清理缓存
		clearRedis(content.getCategoryId());
		
		return TaotaoResult.ok();
	}

	@Override
	public TaotaoResult updateContent(TbContent content) throws Exception {
		Date date = new Date();
		content.setUpdated(date);
		
		contentMapper.updateByPrimaryKeySelective(content);
		
		//清理缓存
		clearRedis(content.getCategoryId());
		
		return TaotaoResult.ok();
	}

	@Override
	public TaotaoResult removeContent(Long id) throws Exception {
		if(id==null) {
			return TaotaoResult.build(400, "参数错误");
		}
		TbContent content = contentMapper.selectByPrimaryKey(id);
		if(content==null)
			return TaotaoResult.build(401, "内容不存在");
		//更新
		contentMapper.deleteByPrimaryKey(id);
		
		//清理缓存
		clearRedis(content.getCategoryId());
		return TaotaoResult.ok();
	}
	
	private void clearRedis(Long cid) throws Exception {
		
		String doGet = HttpClientUtil.doGet(REST_BASE_URL+REST_CONTENT_SYN_URL+"/"+cid);
		TaotaoResult doGetResult = JsonUtils.jsonToPojo(doGet, TaotaoResult.class);
		if(doGetResult.getStatus()!=200)
			throw new Exception("缓存清空失败");
	}

}
